

#include "serialDataMan.h"
#include "serial.h"
#ifdef SDCC
#include <malloc.h>
#endif
#include <disp.h>
#include "common.h"

static volatile SDM_FRAMTYPE mType=SDM_FRAMETYPE_NA;
static volatile uchar mDat=0;
static volatile SDM_CALLBACK mCallback=0;
static volatile uint mTimeout=0;
static volatile uint *mTimer=0;

static volatile uchar *sdmCache;

void SDM_QUERY() {
	if( mType==SDM_FRAMETYPE_NA ) return;

	if( mType==SDM_FRAMETYPE_FIXLEN ) {
		if(mTimeout!=0 && (*mTimer)>mTimeout) {
			mType=SDM_FRAMETYPE_NA;
			mCallback("",0);
		}
		else {
			if(SERIAL_UNSAFE_GET(sdmCache,mDat)) {
				mType=SDM_FRAMETYPE_NA;
				mCallback(sdmCache,mDat);
			}
		}
	}
}

void SDM_INIT() {
#if USE_HEAP
	sdmCache=(uchar*)malloc(SDM_HEAP_SIZE*sizeof(uchar));
#else
	static volatile uchar xdata _sdmCache[SDM_HEAP_SIZE];
	sdmCache=_sdmCache;
#endif
}

bool SDM_REGISTER(SDM_FRAMTYPE type, uchar dat, SDM_CALLBACK callback, uint *timer, uint timeout) {
	if(type==SDM_FRAMETYPE_FIXLEN && dat>SERRECBUF_FLOWCTRL_UP) return false;
	mType=type;
	mDat=dat;
	mCallback=callback;
	mTimer=timer;
	mTimeout=timeout;

	*mTimer=0;
	return true;
}
